package com.gis.servlet.user;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

import com.gis.bean.User;
import com.gis.dao.UserDao;
import com.gis.util.Constant;
import com.gis.util.JDBCUtils;
import com.gis.util.ResponseUtil;
import com.gis.util.RestResponse;

import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.json.JSONUtil;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
	UserDao userDao = new UserDao();

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String username = req.getParameter("username");
		String password = req.getParameter("password");
		// 与数据库的用户信息进行比对
		QueryRunner qr = new QueryRunner(JDBCUtils.getC3p0DateSource());
		
		try {
			User user = qr.query("select id, username, password from tb_user where username = ?", new BeanHandler<User>(User.class), username);
			if (user == null) {
				ResponseUtil.writeJson(resp, RestResponse.fail(Constant.USER_NOT_EXIST));
				return;
			} else {
//				if (!DigestUtil.md5Hex(password).equals(user.getPassword())) {
				if (!password.equals(user.getPassword())) {
					ResponseUtil.writeJson(resp, RestResponse.fail(Constant.PASSWORD_ERROR));
					return;
				}
			}
			// 用户登录成功之后 将用户的信息和权限列表保存在session
			HttpSession session = req.getSession();
			session.setAttribute("id", user.getId());
			session.setAttribute("username", username);
			session.setAttribute("permissions", userDao.getPermissions(username));
			ResponseUtil.writeJson(resp, RestResponse.success(Constant.LOGIN_SUCCESS, JSONUtil.toBean("{'cookie': 'JSESSIONID=" +session.getId()+ "'}", Object.class)));
			return;
		} catch (SQLException e1) {
			e1.printStackTrace();
			return;
		}
	}
	
	

}
